﻿using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public enum JsonType
{
    JsonUtility,
    LitJson
}

public static class JsonManager
{
    public static void SaveData(object data, string fileName, bool localPath = true, JsonType jsonType = JsonType.LitJson)
    {
        string path = (localPath ? Application.persistentDataPath : Application.streamingAssetsPath) + "/" + fileName + ".json";
        switch (jsonType)
        {
            case JsonType.JsonUtility:
                File.WriteAllText(path, JsonUtility.ToJson(data));
                break;
            case JsonType.LitJson:
                File.WriteAllText(path, JsonMapper.ToJson(data));
                break;
        }
    }
    public static T LoadData<T>(string fileName, JsonType jsonType = JsonType.LitJson) where T : new()
    {
        string path = Application.persistentDataPath + "/" + fileName + ".json";
        if (!File.Exists(path))
        {
            path = Application.streamingAssetsPath + "/" + fileName + ".json";
            if (!File.Exists(path))
            {
                return new T();
            }
        }
        switch (jsonType)
        {
            case JsonType.JsonUtility:
                return JsonUtility.FromJson<T>(File.ReadAllText(path));
            case JsonType.LitJson:
                return JsonMapper.ToObject<T>(File.ReadAllText(path));
        }
        return default(T);
    }

}
